import { TOKEN } from './../../constant/index'
/*
 * @Author: liuxiao
 * @Date: 2024-08-25 01:26:14
 * @Last Modified by: liuxiao
 * @Last Modified time: 2023-09-04 01:41:00
 * ps:使用async和await实现
 */
//创建用户相关的小仓库 --

import { reqLogin } from '@/api/user'
import { loginFormData, loginResponseData } from '@/api/user/type'
import { getItem, setItem } from '@/utils/storage'
import { get } from 'http'
import { defineStore } from 'pinia'
import { computed, reactive, ref } from 'vue'

export const useUserStore = defineStore('User3', () => {
  //ref() 就是 state 属性
  const state = reactive({
    token: getItem(TOKEN) || ''
  })

  const token = ref(getItem(TOKEN) || '')

  const userInfo = reactive({})

  const doubleCount = computed(() => {
    return state
  })

  //function 相当于actions
  const login = async (data: loginFormData) => {
    let res: loginResponseData = await reqLogin(data)
    if (res.code == 0) {
      console.log(res.data.token)
      //if (res.code === 0)
      //将token存储到仓库
      state.token = res.data.token
      //将token存储到本地
      setItem(TOKEN, res.data.token)
      //能保证async函数返回成功的promise
      return 'ok'
      //UserState.value.token = res.data.token
    }
    //登录请求,使用then实现
    // return new Promise((resolve, reject) => {
    //   reqLogin(data)
    //     .then((data: any) => {
    //       console.log(data, 'data')
    //       if (data.code == 0) {
    //         // console.log(data, 'data')
    //         // this.token = data.data as string
    //         // //本地存储一份
    //         // SET_TOKEN(data.data)
    //         return resolve('登录成功！，正在跳转。。。')
    //       } else if (data.code == 1) {
    //         console.log('hahah')
    //         //return reject(data.msg)
    //       }
    //     })
    //     .catch((err) => {
    //       //处理错误情况
    //       return reject(err.msg)
    //     })
    // })
  }

  //获取用户信息方法
  const getUserInfo = async () => {
    console.log('123')
  }

  //对外暴漏
  return { token, state, userInfo, doubleCount, login, getUserInfo }
})
